﻿using Dapr.Actors.Runtime;
using Kevin.Dapr.IActors;

namespace Kevin.Dapr.Actors
{
    public class SeckillActor : Actor, ISeckillActor
    {
        private readonly RedisHelper _redisHelper;

        public SeckillActor(ActorHost host, RedisHelper redisHelper) : base(host)
        {
            this._redisHelper = redisHelper;
        }


        public async Task AddOrder()
        {
            var result = GetSku().Result;
            if (result > 0)
            {
                Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                // 添加订单数
                _redisHelper.GetDatabase().StringIncrement("OrderNum");
                // 更新库存数
                await _redisHelper.GetDatabase().StringDecrementAsync("SkuNumber");
            }

            await Task.FromResult(long.Parse("-1"));
        }

        public Task<long> GetSku()
        {
            var data = Convert.ToInt64(_redisHelper.GetDatabase().StringGet("SkuNumber").ToString());
            Console.WriteLine($"----------库存:{data}----------");
            return Task.FromResult(data);
        }

        public async Task InitSku(string actorid,long number)
        {
            await StateManager.SetStateAsync("init", actorid);
            await _redisHelper.GetDatabase().StringSetAsync("SkuNumber", number);
            await _redisHelper.GetDatabase().StringSetAsync("OrderNum", 0);
        }
    }
}